package hu.rsc.feeds.client.gui;

import hu.rsc.feeds.client.data.Dictionary;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;

public class Countdown extends Composite {
    private static final int DEF_COUNT = 300;
    int count = DEF_COUNT;
    private Label countdownLabel = new Label();
    private List<CountdownListener> listeners = new ArrayList<CountdownListener>();

    Timer timer = new Timer() {
	@Override
	public void run() {
	    if (Countdown.this.count == 0) {
		Countdown.this.count = DEF_COUNT;
		notifyListeners();
	    }
	    Countdown.this.countdownLabel.setText(Integer.toString(Countdown.this.count));
	    Countdown.this.count--;
	}
    };

    public Countdown() {
	Label label = new Label();
	label.setText(Dictionary.getEntry(Dictionary.LABEL_COUNTDOWN, label));
	HorizontalPanel hp = new HorizontalPanel();
	hp.add(label);
	label.addStyleName("countdown");
	this.countdownLabel.addStyleName("countdown");
	this.countdownLabel.setText("N/A");
	hp.add(this.countdownLabel);
	initWidget(hp);
    }

    public void addListener(CountdownListener listener) {
	this.listeners.add(listener);
    }

    public void start() {
	this.count = DEF_COUNT;
	this.timer.scheduleRepeating(1000);
    }

    public void stop() {
	this.countdownLabel.setText("N/A");
	this.timer.cancel();
    }

    private void notifyListeners() {
	for (CountdownListener listener : this.listeners) {
	    listener.onCountdownEnd();
	}
    }
}